package com.cuit.blog.service;

import java.util.List;

import exception.UserAlreadyExistsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.cuit.blog.dao.ArticletypeRespository;
import com.cuit.blog.dao.UserRepository;
import com.cuit.blog.entity.Articletype;
import com.cuit.blog.entity.User;

import jakarta.transaction.Transactional;

@Service
@Transactional
public class UserService {
    @Autowired
    UserRepository userRespository;

    /**
     * 查找所有
     * @return
     */
    public List<User> findAll() {
        return userRespository.findAll();
    }

    /**
     * 分页查找
     * @return
     */
    public Page<User> findAllByPage(int pageIndex, int pageSize) {
        // 排序
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        // 分页
        Pageable pageable = PageRequest.of(pageIndex, pageSize, sort);
        // 分页查询
        Page<User> userPage = userRespository.findAll(pageable);
        return userPage;
    }

    /**
     * 查找某条记录
     *
     * @param username, pwd
     * @return
     */
    public User login(String username, String pwd) {
        return userRespository.findByUsernameAndPwd(username, pwd);
    }

    /**
     * 注册新用户
     *
     * @param user
     * @throws UserAlreadyExistsException
     */
    public boolean register(User user) throws UserAlreadyExistsException {
        // 验证用户名长度
        if (user.getUsername().length() < 3 || user.getUsername().length() > 15) {
            throw new IllegalArgumentException("Username must be between 3 and 15 characters.");
        }

        // 验证密码长度
        if (user.getPwd().length() < 6 || user.getPwd().length() > 15) {
            throw new IllegalArgumentException("Password must be between 6 and 15 characters.");
        }

        // 检查用户名是否已存在
        if (userRespository.findByUsername(user.getUsername()) != null) {
            throw new UserAlreadyExistsException("Username already exists.");
        }

        // 保存用户信息
        userRespository.save(user);
        return true;
    }


}
